package com.example.servlet;

import com.example.beans.UserBean;
import com.example.dao.UserDAO;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/updateUser")
public class UpdateUserServlet extends HttpServlet {
    private final UserDAO userDAO = new UserDAO(); // 提前创建 UserDAO 实例，避免重复创建

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        UserBean user = new UserBean();

        // 处理用户 ID 转换异常
        try {
            user.setUserid(Integer.parseInt(request.getParameter("userid")));
        } catch (NumberFormatException e) {
            response.sendRedirect("change.jsp?error=user_id_format");
            return;
        }

        // 获取其他参数，可添加空值校验（根据需求）
        user.setName(request.getParameter("name"));
        user.setPassword(request.getParameter("password"));
        user.setEmail(request.getParameter("email"));

        // 执行更新
        try {
            userDAO.updateUser(user);
        } catch (Exception e) {
            // 可记录日志，并重定向回修改页提示更新失败
            response.sendRedirect("change.jsp?error=update_failed");
            return;
        }

        response.sendRedirect("userinfo.jsp");
    }
}